{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<b>Sell Lemonade like a Pro with Gemini and Google Sheets</b>\n",
        "\n",
        "Are you an aspiring Lemonade baron? Or maybe trying to sell something else to your friends and family? Use Gemini to create pitches customized to the people you think who most love lemons."
      ],
      "metadata": {
        "id": "ZWhWniBGu3_Y"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Authenticate and grant Colab access to your spreadsheets for this session\n",
        "\n",
        "from google.colab import auth\n",
        "auth.authenticate_user()\n",
        "\n",
        "import gspread\n",
        "from google.auth import default\n",
        "creds, _ = default()\n",
        "\n",
        "gc = gspread.authorize(creds)"
      ],
      "metadata": {
        "id": "_oO7-MlMpWd2",
        "cellView": "form"
      },
      "execution_count": 1,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Configure Gemini API key\n",
        "\n",
        "#Access your Gemini API key\n",
        "\n",
        "import google.generativeai as genai\n",
        "from google.colab import userdata\n",
        "\n",
        "gemini_api_secret_name = 'GOOGLE_API_KEY'  # @param {type: \"string\"}\n",
        "\n",
        "try:\n",
        "  GOOGLE_API_KEY=userdata.get(gemini_api_secret_name)\n",
        "  genai.configure(api_key=GOOGLE_API_KEY)\n",
        "except userdata.SecretNotFoundError as e:\n",
        "   print(f'Secret not found\\n\\nThis expects you to create a secret named {gemini_api_secret_name} in Colab\\n\\nVisit https://makersuite.google.com/app/apikey to create an API key\\n\\nStore that in the secrets section on the left side of the notebook (key icon)\\n\\nName the secret {gemini_api_secret_name}')\n",
        "   raise e\n",
        "except userdata.NotebookAccessError as e:\n",
        "  print(f'You need to grant this notebook access to the {gemini_api_secret_name} secret in order for the notebook to access Gemini on your behalf.')\n",
        "  raise e\n",
        "except Exception as e:\n",
        "  # unknown error\n",
        "  print(f\"There was an unknown error. Ensure you have a secret {gemini_api_secret_name} stored in Colab and it's a valid key from https://makersuite.google.com/app/apikey\")\n",
        "  raise e\n",
        "\n",
        "model = genai.GenerativeModel('gemini-pro')"
      ],
      "metadata": {
        "id": "yFv1abRcv2P2",
        "cellView": "form"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#Create a spreadsheet\n",
        "\n",
        "In [drive.google.com](drive.google.com) create a spreadsheet with the data Gemini needs: name, relationship, and context about that person and your relationship to help personalize a message."
      ],
      "metadata": {
        "id": "UoAAnPPPSXNn"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Enter the url of a spreadsheet to import and subject to sell\n",
        "\n",
        "spreadsheet_url = \"https://docs.google.com/spreadsheets/d/1E28W9EUvGn90zui8tG13PtnTaVbC_4VkbY1_NEaA2Ec/edit#gid=0\" #@param {type:\"string\"}\n",
        "sales_topic = \"Lemonade\" #@param {type:\"string\"}\n",
        "\n",
        "worksheet = gc.open_by_url(spreadsheet_url).sheet1\n",
        "\n",
        "# get_all_values gives a list of rows.\n",
        "rows = worksheet.get_all_values()\n",
        "print(rows[0:5])"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "cellView": "form",
        "id": "gGnYhGtfyb8c",
        "outputId": "fece495a-3eb9-44e5-ebef-aa8ca8adee49"
      },
      "execution_count": 5,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "[['Name', 'Relationship', 'Context'], ['Corrie', 'Coworker', 'Loves sewing. Unclear love of lemonade.'], ['Rishi', 'Neighbor', 'Loves baked goods. Incredible chef.'], ['Bill', 'Town mayor', 'Owes me a favor for not installing those speed bumps yet.']]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Use Gemini to suggest what to say to pitch them\n",
        "\n",
        "rows[0].append('Pitch')\n",
        "\n",
        "#skip the title row\n",
        "for row in rows[1:]:\n",
        "  prompt = \"I'm selling %s. Can you suggest a short paragraph of text for how I might best pitch them on buying? I'm writing a note to %s my %s. Here's some context about them: %s.\" % (sales_topic, row[0], row[1], row[2])\n",
        "\n",
        "  response = model.generate_content(prompt)\n",
        "  row.append(response.text)\n",
        "\n",
        "#print out the results nicely\n",
        "from IPython.display import Markdown\n",
        "import textwrap\n",
        "\n",
        "def to_markdown(text):\n",
        "  text = text.replace('•', '  *')\n",
        "  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))\n",
        "\n",
        "to_markdown(''.join([row[3]+'\\n\\n' for row in rows[1:]]))"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 347
        },
        "cellView": "form",
        "id": "KuvZs9W1USEq",
        "outputId": "7eef662a-481b-4d47-cd66-4177f0992dc7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<IPython.core.display.Markdown object>"
            ],
            "text/markdown": "> Corrie, I'm offering you a delicious and refreshing treat - my lemonade! You will surely love its tangy and sweet flavor, which I made with fresh lemons and pure water. Not only is it a great way to cool off on a hot day, but it's also a perfect match for your sewing hobby. Imagine sipping on my lemonade while you create your beautiful masterpieces - it will enhance your creativity and make the whole experience even more enjoyable. Don't miss out on this opportunity to indulge in a delightful drink that will complement your passions. Try it now and let the taste of my lemonade inspire your next sewing project!\n> \n> Hi Rishi, \n> \n> I'm back again with my homemade lemonade, and this time, I've got a special treat for you - a batch that's been infused with a hint of lemon zest and fresh mint. I know you're an incredible chef with a sweet tooth, so I thought you might enjoy this refreshing and slightly tangy twist on a classic.\n> \n> Would you care to try a glass? I'm sure it'll be a great complement to your culinary creations.\n> \n> Dear Mayor Bill,\n> \n> I would love to sell you some of my delicious, refreshing lemonade! Given that you owe me a favor for not installing those speed bumps, I imagine this should solidify our future business relationship. Not only is my lemonade a thirst-quenching treat, but it also supports our local community. Please support our local youth entrepreneurship and indulge in a cup of my refreshing lemonade! \n> \n> Sincerely,\n> \n> [Your Name]\n> \n"
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "#(OPTIONAL) Write the notes back to your spreadsheet\n",
        "\n",
        "This only works for a spreadsheet you own, not the example sheet!"
      ],
      "metadata": {
        "id": "eTLOLFP7dYuW"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Write the notes back to your spreadsheet\n",
        "\n",
        "#this chooses which column to write to\n",
        "col = len(rows[0])\n",
        "start_cell = chr(col + 64) + '1'\n",
        "\n",
        "#write the column\n",
        "try:\n",
        "  worksheet.update(start_cell, [[row[3]] for row in rows])\n",
        "except Exception as e:\n",
        "  print('There was an error writing to your spreadsheet. Make sure you have permissions to edit the spreadsheet.')\n",
        "  raise e"
      ],
      "metadata": {
        "cellView": "form",
        "id": "-jc_4i12Ys3C"
      },
      "execution_count": 7,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#The notes are in!\n",
        "\n",
        "Go check your spreadsheet in Drive - there's a new column with the pitches Gemini created. Good luck with your lemonade sales!"
      ],
      "metadata": {
        "id": "FB419aaKeMFt"
      }
    }
  ]
}